package com.example.index.download

import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.FileProvider
import androidx.recyclerview.widget.RecyclerView
import com.cat.annotation.Index
import com.example.index.BuildConfig
import com.example.index.R
import com.example.index.reflect.BaseListActivity
import es.dmoral.toasty.Toasty
import kotlinx.android.synthetic.main.activity_base_list.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File


@Index(keywords = "FileDownLoad/文件下载/断点下载", link = "https://github.com/lingochamp/FileDownloader")
open class FileDownLoadActivity : BaseListActivity<FileProgress, FileDownLoadActivity.FileDownLoadViewHolder>() {


    val apkDownloadUrls = arrayListOf(

        Pair(
            "https://qd.myapp.com/myapp/qqteam/AndroidQQ/mobileqq_android.apk",
            "QQ123.apk"
        ),
        Pair(
            "https://dldir1.qq.com/weixin/android/weixin706android1480.apk",
            "微信123.apk"
        )

    )

    val dataList = arrayListOf<FileProgress>()

    val dummyPayLoad = listOf(Object())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        smartRefreshLayout.setEnableLoadMore(false)
        smartRefreshLayout.setEnableRefresh(false)
        init()
        EventBus.getDefault().register(this)
    }

    private fun init() {


        apkDownloadUrls.forEach {
            dataList.add(FileProgress(it.second, it.first, 0, 0))
        }

        onRefreshData(dataList)
    }


    override fun getLayoutRes() = R.layout.item_file_download

    override fun startLoadMore() {

    }

    override fun startRefresh() {

    }

    val TAG = "FileDownLoad"

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        if (item?.itemId == R.id.deleteAllFile) {
            apkDownloadUrls.forEach {
                val file = File(File(filesDir, File.separator + "downloads"), it.second)
                Log.i(TAG, "onOptionsItemSelected: ${file.length()}")
                file.delete()
            }
            Toasty.info(this, "文件全部删除", Toast.LENGTH_SHORT).show()
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.delete_file, menu)
        return super.onCreateOptionsMenu(menu)
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onFileProgressChange(event: ProgressEvent) {
        dataList.forEachIndexed { index, fileProgress ->
            if (fileProgress.url === event.url) {
                fileProgress.progress = event.progress
                fileProgress.status = 1
                adapter().notifyItemChanged(index, dummyPayLoad)

                if (event.progress == 100) {
                    installAPK(event.apkFile!!, event.apkFile!!.name)
                }

                return@forEachIndexed
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onFileDownLoadPause(event: PauseEvent) {
        dataList.forEachIndexed { index, fileProgress ->
            if (fileProgress.url == event.url) {
                fileProgress.status = 2
                adapter().notifyItemChanged(index, dummyPayLoad)
                return@forEachIndexed
            }
        }
    }


    var onItemClickListener = View.OnClickListener { v ->

        val position = recyclerView.getChildViewHolder(v.parent.parent.parent as View).adapterPosition

        val fileProgress = dataList[position]

        if (fileProgress.status == 0 || fileProgress.status == 2)
            FileDownLoadManager.download(fileProgress.url, fileProgress.name, File(filesDir, "downloads").absolutePath)
        else FileDownLoadManager.pause(fileProgress.url)

    }


    /**
     * 部分刷新
     */
    override fun onBindViewHolder(holder: FileDownLoadViewHolder, item: FileProgress, payLoads: MutableList<Any>) {

        if (payLoads.isEmpty()) {

            holder.fileName.text = item.name
            holder.button.text = item.statusText()
            holder.button.setOnClickListener(onItemClickListener)

        } else {

            holder.progress.progress = item.progress
            holder.button.text = item.statusText()
        }

    }


    class FileDownLoadViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val fileName = itemView.findViewById<TextView>(R.id.file_name)
        val progress = itemView.findViewById<ProgressBar>(R.id.progress_bar)
        val button = itemView.findViewById<Button>(R.id.button)
    }


    protected fun installAPK(file: File, apkName: String) {
        if (!file.exists())
            return
        val intent = Intent(Intent.ACTION_VIEW)
        val uri: Uri

        // 判断版本大于等于7.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //坑 http://www.jianshu.com/p/c58d17073e65
            val newPath = File(filesDir.path + "/downloads")
            if (!newPath.exists()) {
                //通过file的mkdirs()方法创建 目录中包含却不存在的文件夹
                newPath.mkdirs()
            }
            val path = newPath.path + "/" + apkName
            val oldPath = file.path
//            copyFile(oldPath, path)
            val newfile = File(path)
            // 即是在清单文件中配置的authorities
            uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID, file)
            // 给目标应用一个临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK)

        } else {
            uri = Uri.parse("file://$file")
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        }
        intent.setDataAndType(uri, "application/vnd.android.package-archive")
        //在服务中开启activity必须设置flag,后面解释
        startActivity(intent)
    }


    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}
